<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-05-21 10:43:30
 * @LastEditors: Sam
 * @LastEditTime: 2020-10-21 16:01:25
 */ 
namespace app\api\model;
use think\Db;
use think\Model;
use traits\ModelTrait;
use think\Cache;
use think\Session;
use services\RedisService;
use think\facade\Request;

class User extends Model{

    private  static $token;
    protected $autoWriteTimestamp = true;
    use ModelTrait;
   /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
       public static function getUser($token)
    {
        $redis = RedisService::getInstance();
        if(!$user_redis =  $redis->h_getAll('userInfo',$token)) show(201,'未登录');
        return self::getByOpenid($user_redis['openid']);
    }

        /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {

        $code   = Request::post('code');
        // 微信登录 获取session_key
        $session = $this->wxlogin($code);
        // 自动注册用户
        if($session && $session['openid']){
            $user_id = $this->register($session['openid']);
            // 生成token (session3rd)
            $this->token = $this->token($session['openid']);
            // 记录缓存, 7天   
            Session::set($this->token, $session);
            $redis = RedisService::getInstance();
            $redis->hMset('userInfo',$this->token, $session);
            return $this->token;
        }
        show(201, '登录失败');
   
    }

        /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        if (empty($code)) {
            show(201, '缺少参数code');
        }
        // 获取当前小程序信息
        $config = config('applet');
        $appid = $config['appId'];
        $secret = $config['appSecret'];
        try {
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
            $res = httpRequest($url);
            $open = json_decode($res, true);
            if(isset($open['errcode'])){
                exception($open['errmsg']);
            }
        } catch (\Exception $e) {
            show(201, $e->getMessage());
        }
        return $open;
    }

        /**
     * 获取token
     * @return mixed
     */
    public  static function getToken()
    {
        return self::$token;
    }

        /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        $config    = config('applet');
        $wxapp_id  = $config['appId'];
        // 生成一个不会重复的随机字符串
        // $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$openid}_{$salt}");
    }

       /**
     * 自动注册用户
     * @param $open_id
     * @param $userInfo
     * @return mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function register($open_id)
    {
        if (!$user = self::get(['openid' => $open_id])) {
            $user = self::create(['openid'=>$open_id]);    
        }
        return $user->id;
    }
    
}